package com.demo.blog;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.demo.util.BCSUtils;
import com.demo.util.HtmlFilter;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.render.JsonRender;

/**
 * BlogController
 * 注意：在实际项目中业务与sql需要写在Model中，此demo仅为示意,故将sql写在了Controller中
 */
@Before(BlogInterceptor.class)
public class BlogController extends Controller {
	
	private static final Log log = LogFactory.getLog(BCSUtils.class);
	
	public void index() {
		setAttr("blogPage", Blog.dao.paginate(getParaToInt(0, 1), 10, "select *", "from blog order by id asc"));
		render("blog.html");
	}
	
	public void add() {
	}
	
	@Before(BlogValidator.class)
	public void save() {
	    String title = getPara("blog.title");
        String content = getPara("blog.content");
        new Blog().set("title", HtmlFilter.getText(title)).set("content", HtmlFilter.getBasicHtmlandimage(content)).save();
		redirect("/blog");
	}
	
	public void edit() {
		setAttr("blog", Blog.dao.findById(getParaToInt()));
	}
	
	@Before(BlogValidator.class)
	public void update() {
		getModel(Blog.class).update();
		redirect("/blog");
	}
	
	public void delete() {
		Blog.dao.deleteById(getParaToInt());
		redirect("/blog");
	}
	
	public void editor(){
		HttpServletRequest httpRequest = getRequest();
		ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator iter = upload.getItemIterator(httpRequest);
            while (iter.hasNext()) {
                FileItemStream item = iter.next();
                InputStream stream = item.openStream();
                if ( !item.isFormField() ) {
                    String fileName = item.getName();
                    String contentType = item.getContentType();
                    byte[] buffer = new byte[1024 * 1024];
                    int  length = 0, bytesRead = -1;
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    while ((bytesRead = stream.read(buffer)) != -1) {
                        baos.write(buffer, 0, bytesRead);
                        length += bytesRead;
                    }
                    byte[] data = baos.toByteArray();
                    ByteArrayInputStream bis = new ByteArrayInputStream(data);
                    // 更改文件名
                    fileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
                    if (BCSUtils.uploadByInputStream(bis, contentType, length, fileName)) {
                        String url = "http://bcs.duapp.com/jfinaldemo/";
                        setAttr("error", 0);
                        setAttr("url", url + fileName);
                        render(new JsonRender(new String[] { "error", "url" }).forIE());
                        return;
                    } 
                } 
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }
        setAttr("error", 1);
        setAttr("message", "上传出错，请稍候再试！");
        render(new JsonRender(new String[] { "error", "message" }).forIE());
	}
}


